<template>
  <div class="timeRestrict no_copy">
    <i class="el-icon-date" @click="handleStart"></i>
    <span class="txtTime" @click="handleStart">
      <template v-if="activetimeRestrictShow.function=='absolute_time'">
        <span
          class="block"
          v-if="activetimeRestrictShow.params[0]!==null"
        >{{activetimeRestrictShow.params[0]}}</span>
        <span class="block" v-else>暂无时间跨度</span>
      </template>
      <template v-else>
        <span class="block">{{timeShow(activetimeRestrictShow.params[0])}}</span>
      </template>
      <span
        :style="{margin:'0 0px'}"
        v-if="(activetimeRestrictShow.params[1]=='last_0_day')&&(activetimeRestrictShow.params[0]=='last_0_day')"
      ></span>
      <span
        :style="{margin:'0 0px'}"
        v-else-if="(activetimeRestrictShow.params[1]=='last_1_day')&&(activetimeRestrictShow.params[0]=='last_1_day')"
      ></span>
      <span
        :style="{margin:'0 0px'}"
        v-else-if="!activetimeRestrictShow.params[1]||!activetimeRestrictShow.params[0]"
      ></span>
      <span :style="{margin:'0 12px'}" v-else>至</span>
      <template v-if="activetimeRestrictShow.function=='absolute_time'">
        <span class="block">{{activetimeRestrictShow.params[1]}}</span>
      </template>
      <template v-else>
        <span
          class="block"
          v-if="activetimeRestrictShow.params[1]!==activetimeRestrictShow.params[0]"
        >{{timeShow(activetimeRestrictShow.params[1])}}</span>
      </template>
    </span>
    <div
      class="chassisBox"
      :style="{height:chassisBool?'7rem':'0',border:chassisBool?'1px solid #ebeef5':'0px solid #ebeef5'}"
    >
      <section>
        <div class="left">
          <header>快捷选择</header>
          <span
            :class="_i.label==quickOptions?'active':''"
            @click="quickOptionsClick(_i.label)"
            v-for="_i in quickOptionArr"
            :key="_i.label"
          >{{_i.value}}</span>
        </div>
        <div class="right">
          <el-tabs
            v-model="activetimeRestrict.function"
            @tab-click="el_time_change(activetimeRestrict.function)"
          >
            <el-tab-pane label="静态时间" name="absolute_time">
              <div class="timeBox">
                <div class="lefttimeBox" :style="{borderRight:'none',width:'auto'}">
                  <div id="absoluteTimeLayDateLeft"></div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="动态时间" name="dynamic_time">
              <div class="timeBox">
                <div class="lefttimeBox">
                  <header>
                    <span
                      :style="{width:'40%'}"
                      @click="dynamicTimeTabChange('start',1)"
                      :class="dynamic_time_tab.start==1?'active':''"
                    >具体时间</span>
                    <span
                      :style="{width:'40%'}"
                      @click="dynamicTimeTabChange('start',2)"
                      :class="dynamic_time_tab.start==2?'active':''"
                    >过去N天</span>
                  </header>
                  <section>
                    <div v-show="dynamic_time_tab.start==1" id="relativeTimeLayDate"></div>
                    <el-input
                      :min="0"
                      @change="dynamicTimeChange($event,0)"
                      type="number"
                      v-model="dynamic_time_input[0]"
                      :style="{width:'90%',margin:'10px auto'}"
                      v-show="dynamic_time_tab.start==2"
                      size="mini"
                    ></el-input>
                  </section>
                </div>
                <div class="righttimeBox">
                  <header>
                    <span
                      :style="{width:'30%'}"
                      @click="dynamicTimeTabChange('end',1)"
                      :class="dynamic_time_tab.end==1?'active':''"
                    >今日</span>
                    <span
                      :style="{width:'30%'}"
                      @click="dynamicTimeTabChange('end',2)"
                      :class="dynamic_time_tab.end==2?'active':''"
                    >昨日</span>
                    <span
                      :style="{width:'30%'}"
                      @click="dynamicTimeTabChange('end',3)"
                      :class="dynamic_time_tab.end==3?'active':''"
                    >过去N天</span>
                  </header>
                  <section>
                    <el-input
                      @change="dynamicTimeChange($event,1)"
                      type="number"
                      :min="0"
                      v-model="dynamic_time_input[1]"
                      :style="{width:'90%',margin:'10px auto'}"
                      v-if="dynamic_time_tab.end==3"
                      size="mini"
                    ></el-input>
                  </section>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </section>
      <footer>
        <el-button size="mini" @click="chassisBool=false" type="primary" plain>取消</el-button>
        <el-button size="mini" @click="submitSend" type="primary">确定</el-button>
      </footer>
    </div>
  </div>
</template>
<script>
import laydate from "./laydate.js";
export default {
  name: "timeRestrict",
  props: {
    timeRestrict: {
      type: Object
    },
    oldTime: {
      type: Array,
      default: () => {
        return [null, null];
      }
    } // 容错处理之前没有动态时间的参数
  },
  watch: {},
  components: {},
  data() {
    return {
      dynamic_time_input: [0, 0], //  动态时间输入绑定值
      quickOptions: null, // 快捷选项当前选中值
      quickOptionArr: [
        {
          value: "今日",
          label: "1"
        },
        {
          value: "昨日",
          label: "2"
        },
        {
          value: "本周",
          label: "3"
        },
        {
          value: "上周",
          label: "4"
        },
        {
          value: "本月",
          label: "5"
        },
        {
          value: "上月",
          label: "6"
        },
        {
          value: "本年",
          label: "7"
        },
        {
          value: "去年",
          label: "8"
        },
        {
          value: "过去7天",
          label: "9"
        },
        {
          value: "过去14天",
          label: "10"
        },
        {
          value: "过去30天",
          label: "11"
        },
        {
          value: "过去60天",
          label: "12"
        },
        {
          value: "过去90天",
          label: "13"
        },
        {
          value: "过去180天",
          label: "14"
        }
      ], // 快捷选项可选值
      activeTab: "absolute_time", //  时间tab
      dynamic_time_tab: {
        start: 2,
        end: 3
      }, // 动态时间下的tab绑定值
      activetimeRestrict: {
        function: "absolute_time", // dynamic_time  ：  动态时间     absolute_time  ：  绝对时间
        params: [null, null] // last_数字_跨度
      }, // 当前操作的时间变量
      activetimeRestrictShow: {
        function: "absolute_time", // dynamic_time  ：  动态时间     absolute_time  ：  绝对时间
        params: [null, null] // last_数字_跨度
      }, // 当前控件显示日期
      chassisBool: false //  日期选择折叠开关
    };
  },
  methods: {
    // 打开控制面板
    handleStart() {
      // if (this.chassisBool) {
      //   return;
      // }
      this.chassisBool = !this.chassisBool;
    },
    // 确认点击函数
    submitSend() {
      console.log(Number(this.dynamic_time_input[0]),Number(this.dynamic_time_input[1]),'667788')
      if (
        Number(this.dynamic_time_input[0]) < 0 ||
        Number(this.dynamic_time_input[1]) < 0 ||
        Number(this.dynamic_time_input[0]) < Number(this.dynamic_time_input[1])
      ) {
        if(this.dynamic_time_tab.start==2){
          this.$message({
            message: "请选择正确的时间范围。。。111",
            type: "warning"
          });
          return;
        } 
      }
      if (
        !this.activetimeRestrict.params[0] ||
        !this.activetimeRestrict.params[1]
      ) {
        this.$message({
          message: "请选择正确的时间范围。。。222",
          type: "warning"
        });
        return;
      }
      let sendTimeArr = [null, null]; // 向外发送的用来使用的时间数组
      if (this.activetimeRestrict.function == "absolute_time") {
        let num_z = new Date(this.activetimeRestrict.params[0]).getTime();
        let num_o = new Date(this.activetimeRestrict.params[1]).getTime();
        if (!num_z || !num_o || num_z > num_o) {
          this.$message({
            message: "请选择正确的时间范围。。。333",
            type: "warning"
          });
          return;
        } else {
          sendTimeArr = [
            this.activetimeRestrict.params[0],
            this.activetimeRestrict.params[1]
          ];
        }
      }

      if (this.activetimeRestrict.function == "dynamic_time") {
        let num_one = null;
        let num_Two = null;
        if (this.activetimeRestrict.params[0].split("_").length == 3) {
          num_one = parseInt(
            Number(this.activetimeRestrict.params[0].split("_")[1])
          );
          num_one = new Date(
            new Date().getTime() - num_one * 24 * 60 * 60 * 1000
          );
          num_one =
            num_one.getFullYear() +
            "-" +
            (num_one.getMonth() + 1 < 10
              ? "0" + (num_one.getMonth() + 1)
              : num_one.getMonth() + 1) +
            "-" +
            (num_one.getDate() < 10
              ? "0" + num_one.getDate()
              : num_one.getDate());
        }else{
          num_one = this.activetimeRestrict.params[0]
        }
        num_Two = parseInt(
          Number(this.activetimeRestrict.params[1].split("_")[1])
        );

        num_Two = new Date(
          new Date().getTime() - num_Two * 24 * 60 * 60 * 1000
        );
        num_Two =
          num_Two.getFullYear() +
          "-" +
          (num_Two.getMonth() + 1 < 10
            ? "0" + (num_Two.getMonth() + 1)
            : num_Two.getMonth() + 1) +
          "-" +
          (num_Two.getDate() < 10
            ? "0" + num_Two.getDate()
            : num_Two.getDate());

        sendTimeArr = [num_one, num_Two];
        
        if( new Date(num_one).getTime() > new Date(num_Two).getTime() ) {
          this.$message({
            message: "请选择正确的时间范围。。。",
            type: "warning"
          });
          return
        }
      }
      this.quickOptions = null;
      this.chassisBool = false;
      this.activetimeRestrictShow = JSON.parse(
        JSON.stringify(this.activetimeRestrict)
      );
      console.log(sendTimeArr, this.activetimeRestrict, "传出");
      this.$emit("change", {
        sendTimeArr,
        timeRestrict: JSON.parse(JSON.stringify(this.activetimeRestrict))
      });
    },
    // 本地控件，根据传入时间，进行参数初始化
    configLocalInit(obj) {
      this.quickOptions = null;
      // 如果传入动态时间参数
      if (obj && obj.function) {
        this.activeTab = obj.function;
      }
      if (
        obj &&
        obj.function == "dynamic_time" &&
        obj.params &&
        obj.params.length == 2
      ) {
        if (obj.params[0] && obj.params[0].split("_").length == 3) {
          this.dynamic_time_input[0] = obj.params[0]
            ? obj.params[0].split("_")[1]
            : null;
        } else {
          this.dynamic_time_tab.start = 1;
        }
        if (obj.params[1]) {
          this.dynamic_time_input[1] = obj.params[1]
            ? obj.params[1].split("_")[1]
            : null;
        }
      }
    },
    // 控件显示
    timeShow(str) {
      if (!str || str.split("_").length != 3) {
        return str;
      }
      let num = str.split("_")[1];
      let {
        weekUnit,
        monthUnit,
        lastdate,
        lastYear,
        lastMonth,
        yearUnit,
        lastYearDay,
        lastMonthUnit
      } = this.unitArrGet();
      if (num == 0) {
        return "今天";
      }
      if (num == 1) {
        return "昨天";
      }
      if (num == weekUnit) {
        return "本周一";
      }
      if (num == weekUnit + 6) {
        return "上周一";
      }
      if (num == weekUnit) {
        return "上周末";
      }
      if (num == monthUnit) {
        return "本月1号";
      }
      if (num == monthUnit + lastMonthUnit) {
        return "上个月1号";
      }
      if (num == monthUnit + 1) {
        return "上个月末";
      }
      if (num == yearUnit) {
        return "1月1号";
      }
      if (num == yearUnit + lastYearDay) {
        return "去年1月1号";
      }
      if (num == yearUnit + 1) {
        return "去年12月31日";
      }
      return "过去" + num + "天";
    },
    // 获取跨度计算值
    unitArrGet() {
      let weekUnit = new Date().getDay(); // 计算周跨度
      weekUnit = weekUnit == 0 ? 6 : weekUnit - 1;
      let monthUnit = new Date().getDate() - 1; // 计算月跨度
      let lastdate = new Date(); // 获取上个月天数
      let lastYear = lastdate.getFullYear();
      let lastMonth = lastdate.getMonth() + 1;
      if (lastMonth == 1) {
        lastMonth = 12;
        lastYear--;
      }
      // 计算年跨度、
      let yearUnit =
        Math.ceil(
          (new Date() - new Date(new Date().getFullYear().toString())) /
            (24 * 60 * 60 * 1000)
        ) - 1;
      // 获取去年天数
      let lastYearDay = new Date().getFullYear() - 1;
      if (
        (lastYearDay % 4 == 0 && lastYearDay % 100 != 0) ||
        lastYearDay % 400 == 0
      ) {
        lastYearDay = 366;
      } else {
        lastYearDay = 365;
      }
      let lastMonthUnit = new Date(lastYear, lastMonth, 0).getDate() + 1;
      return {
        weekUnit,
        monthUnit,
        lastdate,
        lastYear,
        lastMonth,
        yearUnit,
        lastYearDay,
        lastMonthUnit
      };
    },
    // 静态时间 动态时间切换函数
    el_time_change(type) {
      this.activetimeRestrict = {
        function: type,
        params: [null, null]
      };
      if (type == "dynamic_time") {
        this.activetimeRestrict.params = ["last_0_day", "last_0_day"];
        this.dynamic_time_input = [0, 0];
      }
      this.quickOptions = null;
    },
    // 动态时间 tab 切换 点击函数
    dynamicTimeTabChange(key, value) {
      this.dynamic_time_tab[key] = value;
      this.quickOptions = null;
      if (key == "start") {
        this.activetimeRestrict.params[0] = null;
        if (value == 2) {
          this.activetimeRestrict.params[0] = "last_0_day";
          this.dynamic_time_input[0] = 0;
        }
      }
      if (key == "end") {
        this.activetimeRestrict.params[1] = null;
        if (value == 1) {
          this.activetimeRestrict.params[1] = "last_0_day";
        }
        if (value == 2) {
          this.activetimeRestrict.params[1] = "last_1_day";
        }
        if (value == 3) {
          this.activetimeRestrict.params[1] = "last_0_day";
          this.dynamic_time_input[1] = 0;
        }
      }
    },
    // 动态时间输入框更改事件
    dynamicTimeChange(value, index) {
      this.quickOptions = null;
      this.activetimeRestrict.params[index] =
        "last_" + Number(parseInt(value)) + "_day";
    },
    // 快捷选项点击函数
    quickOptionsClick(value) {
      this.quickOptions = value;
      let obj = {
        function: "dynamic_time",
        params: [null, null]
      };
      this.dynamic_time_tab = {
        start: 2,
        end: 3
      };
      let {
        weekUnit,
        monthUnit,
        lastdate,
        lastYear,
        lastMonth,
        yearUnit,
        lastYearDay,
        lastMonthUnit
      } = this.unitArrGet();
      switch (value) {
        case "1":
          obj.params = ["last_0_day", "last_0_day"]; // 今日
          this.dynamic_time_input = [0, 0];
          break;
        case "2":
          obj.params = ["last_1_day", "last_1_day"]; // 昨日
          this.dynamic_time_input = [1, 1];
          break;
        case "3":
          obj.params = ["last_" + weekUnit + "_day", "last_0_day"]; // 本周
          this.dynamic_time_input = [weekUnit, 0];
          break;
        case "4":
          obj.params = [
            "last_" + (weekUnit + 6) + "_day",
            "last_" + weekUnit + "_day"
          ]; // 上周
          this.dynamic_time_input = [weekUnit + 6, weekUnit];
          break;
        case "5":
          obj.params = ["last_" + monthUnit + "_day", "last_0_day"]; // 本月
          this.dynamic_time_input = [monthUnit, 0];
          break;
        case "6":
          obj.params = [
            "last_" + (monthUnit + lastMonthUnit) + "_day",
            "last_" + (monthUnit + 1) + "_day"
          ]; // 上月
          this.dynamic_time_input = [monthUnit + lastMonthUnit, monthUnit + 1];
          break;
        case "7":
          obj.params = ["last_" + yearUnit + "_day", "last_0_day"]; // 本年
          this.dynamic_time_input = [yearUnit, 0];
          break;
        case "8":
          obj.params = [
            "last_" + (yearUnit + lastYearDay) + "_day",
            "last_" + (yearUnit + 1) + "_day"
          ]; // 去年
          this.dynamic_time_input = [yearUnit + lastYearDay, yearUnit + 1];
          break;
        case "9":
          obj.params = ["last_7_day", "last_0_day"]; // 过去7天
          this.dynamic_time_input = [6, 0];
          break;
        case "10":
          obj.params = ["last_14_day", "last_0_day"]; // 过去14天
          this.dynamic_time_input = [13, 0];
          break;
        case "11":
          obj.params = ["last_30_day", "last_0_day"]; // 过去30天
          this.dynamic_time_input = [29, 0];
          break;
        case "12":
          obj.params = ["last_60_day", "last_0_day"]; // 过去60天
          this.dynamic_time_input = [59, 0];
          break;
        case "13":
          obj.params = ["last_90_day", "last_0_day"]; // 过去90天
          this.dynamic_time_input = [89, 0];
          break;
        case "14":
          obj.params = ["last_179_day", "last_0_day"]; // 过去180天
          this.dynamic_time_input = [179, 0];
          break;
      }
      this.activetimeRestrict = obj;
    }
  },
  beforeCreate() {},
  created() {
    // 如果传入动态时间参数字段
    if (this.timeRestrict && this.timeRestrict.function) {
      this.activetimeRestrict = JSON.parse(JSON.stringify(this.timeRestrict));
      this.activetimeRestrictShow = JSON.parse(
        JSON.stringify(this.timeRestrict)
      );
    } else {
      this.activetimeRestrict = {
        function: "absolute_time",
        params: [this.oldTime[0], this.oldTime[1]]
      };
      this.activetimeRestrictShow = JSON.parse(
        JSON.stringify(this.activetimeRestrict)
      );
    }
    this.configLocalInit(this.timeRestrict); // 根据传入参数，进行相关参数初始化
  },
  beforeMount() {},
  mounted() {
    try {
      laydate.render({
        elem: "#absoluteTimeLayDateLeft",
        position: "static",
        // type: "datetime",
        range: true,
        format: "yyyy-MM-dd",
        value:
          this.activetimeRestrict.params[0] +
          " - " +
          this.activetimeRestrict.params[1],
        btns: [],
        change: value => {
          this.activetimeRestrict.params = value.split(" - ");
        }
      });
      laydate.render({
        elem: "#relativeTimeLayDate",
        position: "static",
        // type: "datetime"
        format: "yyyy-MM-dd",
        value: this.activetimeRestrict.params[0],
        btns: [],
        change: value => {
          this.activetimeRestrict.params[0] = value;
        }
      });
    } catch (err) {
      console.log("日期控件初始化失败：", err);
    }
  },
  computed: {}
};
</script>

<style scoped lang="scss">
@import "./laydate.css";
* {
  box-sizing: border-box;
}
.timeBox {
  width: 100%;
  height: calc(7rem - 77px);
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  .righttimeBox,
  .lefttimeBox {
    width: 50%;
    height: 100%;
    position: relative;
    #absoluteTimeLayDateLeft {
      position: relative;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    header {
      width: 100%;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-evenly;
      span {
        font-size: 12px;
        cursor: pointer;
        text-align: center;
        background: #fff;
        border: 1px solid #e0e6ed;
        box-sizing: border-box;
        border-radius: 3px;
        height: 28px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .active {
        background: #04cb94;
        color: #fff;
      }
    }
    section {
      width: 100%;
      height: calc(100% - 41px);
      display: flex;
      #relativeTimeLayDate {
        width: 278px;
        height: 326px;
        position: relative;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
      }
    }
  }
  .lefttimeBox {
    border-right: 1px solid #dcdfe6;
  }
}
.timeRestrict {
  margin: 0px 0.2rem;
  cursor: pointer;
  padding: 0 10px;
  height: 32px;
  display: inline-block;
  background-color: #ffffff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  position: relative;
  .chassisBox {
    position: absolute;
    left: 0;
    top: 36px;
    display: inline-block;
    width: 12.6rem;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
    background-color: #fff;
    transition: all 0.5s ease;
    z-index: 10;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    section {
      width: 100%;
      height: calc(100% - 41px);
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      .left {
        width: 180px;
        height: 100%;
        header {
          font-weight: 500;
          font-size: 13px;
          line-height: 36px;
          color: #1f2d3d;
          height: 36px;
          text-indent: 10px;
        }
        span {
          width: 44%;
          display: inline-block;
          margin: 3px 3% 6px;
          height: 22px;
          background: #edf4fb;
          border-radius: 3px;
          color: #475669;
          cursor: pointer;
          line-height: 22px;
          text-align: center;
          letter-spacing: 2px;
          font-size: 12px;
        }
        .active {
          color: #fff;
          background-color: #04cb94;
        }
      }
      .right {
        width: calc(100% - 181px);
        height: 100%;
        border-left: 1px solid #dcdfe6;
        ::v-deep .el-tabs__item {
          font-weight: 500;
          font-size: 13px;
          line-height: 36px;
          color: #1f2d3d;
          height: 36px;
          text-indent: 10px;
        }
        ::v-deep .el-tabs__header {
          margin-bottom: 0px;
        }
      }
    }
    footer {
      width: 98%;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      border-top: 1px solid #dcdfe6;
      .el-button {
        margin: 0 6px;
        transform: scale(0.8, 0.8);
      }
    }
  }
  i {
    color: #909399;
    line-height: 36px;
    margin: 0 10px 0 0;
    font-size: 14px;
    line-height: 32px;
  }
  .txtTime {
    font-size: 14px;
    letter-spacing: 2px;
    font-weight: 300;
    line-height: 32px;
    color: #1f2d3d;
    padding: 0 6px 0 0;
    margin: 0 6px 0 0;
    display: inline-block;
  }
}
</style>
